// 预约相关API服务
const request = require('../utils/request');

// 创建预约
const createAppointment = (data) => {
  return request.post('/appointment', data);
};

// 取消预约
const cancelAppointment = (id) => {
  return request.post(`/appointment/cancel/${id}`);
};

// 确认预约（医生操作）
const confirmAppointment = (id) => {
  return request.post(`/appointment/confirm/${id}`);
};

// 拒绝预约（医生操作）
const rejectAppointment = (id) => {
  return request.post(`/appointment/reject/${id}`);
};

// 完成预约（医生操作）
const completeAppointment = (id) => {
  return request.post(`/appointment/complete/${id}`);
};

/**
 * 获取预约详情
 * @param {string|number} id - 预约ID
 * @returns {Promise} - 返回预约详情的Promise
 */
const getAppointmentDetail = (id) => {
  console.log('正在获取预约详情，ID:', id);
  return request.get(`/appointment/detail/${id}`)
    .then(res => {
      console.log('预约详情原始数据:', JSON.stringify(res, null, 2));
      
      // 处理返回的数据
      const appointment = res || {};
      
      // 处理用户名称，确保前端能够显示
      if (appointment.userName && !appointment.username) {
        console.log('检测到userName字段，复制到username:', appointment.userName);
        appointment.username = appointment.userName;
      }
      
      // 如果有extraData字段，将其中的属性合并到对象中
      if (appointment.extraData && typeof appointment.extraData === 'object') {
        console.log('处理预约的extraData:', appointment.extraData);
        
        // 将extraData中的所有属性合并到预约对象中
        Object.keys(appointment.extraData).forEach(key => {
          if (!appointment[key]) {
            console.log(`从extraData复制字段 ${key} 到appointment对象:`, appointment.extraData[key]);
            appointment[key] = appointment.extraData[key];
          }
        });
        
        // 特别检查username字段
        if (appointment.extraData.username && !appointment.username) {
          console.log('从extraData中提取username:', appointment.extraData.username);
          appointment.username = appointment.extraData.username;
        }
      }
      
      console.log('处理后的预约详情:', appointment);
      return appointment;
    })
    .catch(err => {
      console.error('预约详情获取失败:', err);
      return {}; // 返回空对象避免前端报错
    });
};

// 获取用户预约列表
const getUserAppointments = (status, page = 1, size = 10) => {
  const params = { page, size };
  
  // 只有当 status 不是 undefined 或 null 时才添加到参数中
  if (status !== undefined && status !== null) {
    params.status = status;
  }
  
  console.log('获取用户预约列表，参数:', params);
  
  return request.get('/appointment/user', params)
    .then(res => {
      console.log('获取用户预约列表成功，原始数据:', JSON.stringify(res, null, 2));
      
      // 处理不同格式的返回结果
      let result;
      if (res && res.records) {
        // 标准分页格式
        result = res;
      } else if (Array.isArray(res)) {
        // 直接返回数组的情况
        result = {
          records: res,
          total: res.length,
          pages: 1,
          current: 1,
          size: res.length
        };
      } else if (res && typeof res === 'object') {
        // 其他对象格式，尝试兼容处理
        console.log('返回格式需要兼容处理:', JSON.stringify(res, null, 2));
        result = {
          records: res.list || res.data || res.content || res.records || [],
          total: res.total || res.totalCount || res.totalElements || 0,
          pages: res.pages || res.totalPages || 1,
          current: res.current || res.currentPage || page,
          size: res.size || size
        };
      } else {
        // 未知格式，返回空结果
        console.warn('未知返回格式或空返回:', res);
        result = {
          records: [],
          total: 0,
          pages: 0,
          current: page,
          size: size
        };
      }
      
      // 确保records是数组
      if (!result.records) {
        result.records = [];
      }
      
      // 处理records中的每一项，确保extraData字段的数据正确合并到对象中
      if (result.records && Array.isArray(result.records)) {
        // 输出预约记录数量
        console.log(`原始预约记录数量: ${result.records.length}`);
        
        result.records = result.records.map(item => {
          if (!item) {
            console.warn('记录项为空, 跳过处理');
            return null;
          }
          
          console.log(`处理预约记录, ID: ${item.id}, 状态: ${item.status}`, item);
          
          const processedItem = { ...item };
          
          // 确保状态是数字类型
          if (processedItem.status !== undefined) {
            processedItem.status = typeof processedItem.status === 'string' 
              ? parseInt(processedItem.status) 
              : processedItem.status;
            console.log(`预约${processedItem.id}的状态处理为: ${processedItem.status}`);
          }
          
          // 如果有extraData字段，将其中的属性合并到对象中
          if (item.extraData && typeof item.extraData === 'object') {
            console.log(`处理预约${item.id}的extraData:`, item.extraData);
            
            // 将extraData中的所有属性合并到预约对象中
            Object.keys(item.extraData).forEach(key => {
              if (!processedItem[key]) {
                processedItem[key] = item.extraData[key];
              }
            });
          }
          
          return processedItem;
        }).filter(item => item !== null);  // 过滤掉处理后为null的项
        
        // 按状态统计预约数量
        const statusCounts = {
          pending: result.records.filter(item => item.status === 0).length,
          confirmed: result.records.filter(item => item.status === 1).length,
          completed: result.records.filter(item => item.status === 2).length,
          cancelled: result.records.filter(item => item.status === 3).length
        };
        console.log('预约状态统计:', statusCounts);
      }
      
      console.log('处理后的预约列表数据:', JSON.stringify(result, null, 2));
      return result;
    })
    .catch(err => {
      console.error('获取用户预约列表失败:', err);
      // 返回一个带有错误信息的结果对象，而不是抛出异常
      console.warn('返回默认空结果');
      return {
        records: [],
        total: 0,
        pages: 0,
        current: page,
        size: size,
        error: err.message || '未知错误'
      };
    });
};

// 获取医生预约列表
const getStaffAppointments = (status, page = 1, size = 10) => {
  const params = { page, size };
  
  // 只有当 status 不是 undefined 或 null 时才添加到参数中
  if (status !== undefined && status !== null) {
    params.status = status;
  }
  
  return request.get('/appointment/staff', params)
    .then(res => {
      // 处理不同格式的返回结果，与getUserAppointments相同
      if (res && res.records) {
        return res;
      } else if (Array.isArray(res)) {
        return {
          records: res,
          total: res.length,
          pages: 1,
          current: 1,
          size: res.length
        };
      } else if (res && typeof res === 'object') {
        return {
          records: res.list || res.data || res.content || [],
          total: res.total || res.totalCount || res.totalElements || 0,
          pages: res.pages || res.totalPages || 1,
          current: res.current || res.currentPage || page,
          size: res.size || size
        };
      } else {
        return {
          records: [],
          total: 0,
          pages: 0,
          current: page,
          size: size
        };
      }
    })
    .catch(err => {
      console.error('获取医生预约列表失败:', err);
      throw new Error('获取医生预约列表失败: ' + (err.message || '未知错误'));
    });
};

// 获取医生今日预约
const getStaffTodayAppointments = (staffId) => {
  return request.get('/appointment/staff/today', { staffId })
    .then(res => {
      console.log('获取医生今日预约成功:', res);
      return res;
    })
    .catch(err => {
      console.error('获取医生今日预约失败:', err);
      // 返回空数组以避免页面崩溃
      return [];
    });
};

// 获取医生预约统计信息
const getStaffAppointmentStatistics = (staffId) => {
  return request.get('/appointment/staff/statistics', { staffId })
    .then(res => {
      console.log('获取医生预约统计成功:', res);
      return res;
    })
    .catch(err => {
      console.error('获取医生预约统计失败:', err);
      // 返回默认统计数据以避免页面崩溃
      return {
        todayCount: 0,
        pendingCount: 0
      };
    });
};

// 获取预约列表（与getUserAppointments相同，但保持命名一致性）
const getAppointmentList = (params = {}) => {
  console.log('获取预约列表，参数:', params);
  return request.get('/appointment/user', params)
    .then(res => {
      console.log('获取预约列表成功，原始数据:', JSON.stringify(res, null, 2));
      
      // 处理不同格式的返回结果
      let result;
      if (res && res.records) {
        // 标准分页格式
        result = res;
      } else if (Array.isArray(res)) {
        // 直接返回数组的情况
        result = {
          records: res,
          total: res.length,
          pages: 1,
          current: 1,
          size: res.length
        };
      } else if (res && typeof res === 'object') {
        // 其他对象格式，尝试兼容处理
        console.log('返回格式需要兼容处理:', JSON.stringify(res, null, 2));
        result = {
          records: res.list || res.data || res.content || res.records || [],
          total: res.total || res.totalCount || res.totalElements || 0,
          pages: res.pages || res.totalPages || 1,
          current: res.current || res.currentPage || params.page || 1,
          size: res.size || params.size || 10
        };
      } else {
        // 未知格式，返回空结果
        console.warn('未知返回格式:', res);
        result = {
          records: [],
          total: 0,
          pages: 0,
          current: params.page || 1,
          size: params.size || 10
        };
      }
      
      // 处理records中的每一项，确保extraData字段的数据正确合并到对象中
      if (result.records && Array.isArray(result.records)) {
        // 输出预约记录数量
        console.log(`原始预约记录数量: ${result.records.length}`);
        
        result.records = result.records.map(item => {
          console.log(`处理预约记录, ID: ${item.id}, 状态: ${item.status}`, item);
          
          const processedItem = { ...item };
          
          // 确保状态是数字类型
          if (processedItem.status !== undefined) {
            processedItem.status = typeof processedItem.status === 'string' 
              ? parseInt(processedItem.status) 
              : processedItem.status;
            console.log(`预约${processedItem.id}的状态处理为: ${processedItem.status}`);
          }
          
          // 如果有extraData字段，将其中的属性合并到对象中
          if (item.extraData && typeof item.extraData === 'object') {
            console.log(`处理预约${item.id}的extraData:`, item.extraData);
            
            // 将extraData中的所有属性合并到预约对象中
            Object.keys(item.extraData).forEach(key => {
              if (!processedItem[key]) {
                processedItem[key] = item.extraData[key];
              }
            });
          }
          
          return processedItem;
        });
        
        // 按状态统计预约数量
        const statusCounts = {
          pending: result.records.filter(item => item.status === 0).length,
          confirmed: result.records.filter(item => item.status === 1).length,
          completed: result.records.filter(item => item.status === 2).length,
          cancelled: result.records.filter(item => item.status === 3).length
        };
        console.log('预约状态统计:', statusCounts);
      }
      
      console.log('处理后的预约列表数据:', JSON.stringify(result, null, 2));
      return result;
    })
    .catch(err => {
      console.error('获取预约列表失败:', err);
      // 返回一个带有错误信息的结果对象
      throw new Error('获取预约列表失败: ' + (err.message || '未知错误'));
    });
};

module.exports = {
  createAppointment,
  cancelAppointment,
  confirmAppointment,
  rejectAppointment,
  completeAppointment,
  getAppointmentDetail,
  getUserAppointments,
  getStaffAppointments,
  getStaffTodayAppointments,
  getStaffAppointmentStatistics,
  getAppointmentList
}; 